const { models } = require('../model')
const axios = require('axios')

async function sendSubscribe (schedule) {
  const hubs = await models.Tophub
    .find({})
    .project({})
    .toArray()
  const channels = await models.MsgChannel
    .find({})
    .project({})
    .toArray()
  // 发送
  for (const channel of schedule.channelIds) {
    // 获取发送通道
    const webhook = channels.filter(e => e._id.toString() === channel)[0].webhook
    // 获取发送信息
    const contents = []
    for (const hid of schedule.hubIds) {
      const hub = hubs.filter(e => e._id.toString() === hid)[0]
      const latestBatch = await models.TophubRankChange.find({}).sort({ _id: -1 }).limit(1).toArray()
      //
      let content = {
        platform: hub.platform,
        type: '热榜排名变化',
        rankUpSay: '新上热点'
      }
      // content.contents = await models.TophubRankChange.find({
      //   platform: hub.platform,
      //   col: hub.col,
      //   batchNew: latestBatch[0].batchNew,
      //   type: content.type,
      //   rankUpSay: content.rankUpSay
      // }).limit(3).toArray()
      // NewContents.push(content)

      content = {
        platform: hub.platform,
        type: '热榜排名变化',
        rankUpSay: '上升最快'
      }
      content.content = await models.TophubRankChange.find({
        platform: hub.platform,
        col: hub.col,
        batchNew: latestBatch[0].batchNew,
        type: content.type,
        rankUp: { $lt: 0 }
      }).sort({ rankUp: 1 }).limit(3).toArray()
      contents.push(content)
    }
    // 包装信息
    const c = 'feishu'
    if (c === 'feishu') {
      const card = template()
      card.header = header('【热榜来啦 · 最近半小时上升最快】')
      const elmts = []
      contents.forEach(c => {
        elmts.push(div(`[${c.platform}]`))
        c.content.forEach(content => {
            const d = div(`[第${content.seqNew}名·${content.rankUpSay} · ${content.title}](${content.url})`)
            elmts.push(d)
            elmts.push(hr())
          }
        )
      })
      elmts.pop()
      card.elements = elmts
      console.log(card)
      axios.post(webhook, {
          msg_type: 'interactive',
          card: card
      })
    } else {
      let message = ''
      for (const hid of schedule.hubIds) {
        const hub = hubs.filter(e => e._id.toString() === hid)[0]
        const latestBatch = await models.TophubRankChange.find({}).sort({ _id: -1 }).limit(1).toArray()
        //
        message += '【一、新上热点及当前排名】'
        let contents = await models.TophubRankChange.find({
          platform: hub.platform,
          col: hub.col,
          batchNew: latestBatch[0].batchNew,
          type: '热榜排名变化',
          rankUpSay: '新上热点'
        }).limit(5).toArray()
        message += `\n${hub.platform}`
        contents.forEach(content => {
          message += `\n第${content.seqNew}名 · ${content.title}`
        })
        //
        message += '\n\n【二、上升最快】'
        contents = await models.TophubRankChange.find({
          platform: hub.platform,
          col: hub.col,
          batchNew: latestBatch[0].batchNew,
          type: '热榜排名变化',
          rankUp: { $lt: 0 }
        }).sort({ rankUp: 1 }).limit(3).toArray()
        if (contents.length === 0) {
          message += '\n无'
        } else {
          message += `\n${hub.platform}`
          contents.forEach(content => {
            message += `\n第${content.seqNew}名 · ${content.rankUpSay} · ${content.title}`
          })
        }
      }
      console.log('message', message)
      axios.post(webhook, {
        msg_type: 'text',
        content: {
          text: message
        }
      })
    }
  }
}

function div (content) {
  const t = {
    tag: 'div',
    text: {
      content: content,
      tag: 'lark_md'
    }
  }
  return t
}

function hr () {
  return {
    tag: 'hr'
  }
}

function img () {
  const img = {
    alt: {
      content: '',
      tag: 'plain_text'
    },
    img_key: 'img_v2_04787a5c-c05f-4032-8a22-eda9cc244acg',
    tag: 'img'
  }
  return img
}
function note () {
  const note = {
    elements: [
      {
        content: '💡本栏目每天早上为你带来回顾，你想在这里看到什么样的帖子？给我们留言吧 😘 ',
        tag: 'plain_text'
      }
    ],
    tag: 'note'
  }
  return note
}

function header (title) {
  const h = {
    template: 'turquoise',
    title: {
      content: title,
      tag: 'plain_text'
    }
  }
  return h
}
function template () {
  const t = {
    config: {
      wide_screen_mode: true
    },
    header: null,
    elements: null
  }
  return t
}

module.exports = {
  sendSubscribe
}
